#include "backgroundsubstraction.h"

BackgroundSubstraction::BackgroundSubstraction() : method(id), fileName("cam"), capture(NULL), proc(allocProcessor(id)) {}

BackgroundSubstraction::~BackgroundSubstraction()
{
    if( proc )
        delete proc;
}

BackgroundSubstraction::BackgroundSubstraction(const BackgroundSubstraction &bs) : method(bs.method), fileName(bs.fileName), capture(NULL), proc(allocProcessor(bs.method)) {}

BackgroundSubstraction& BackgroundSubstraction::operator=(const BackgroundSubstraction &bs)
{
    method   = bs.method;
    fileName = bs.fileName;
    capture  = NULL;
    proc     = allocProcessor(method);
    return (*this);
}

BackgroundSubstraction::BackgroundSubstraction(const Method &_method, const string &_fileName) : method(_method), fileName(_fileName), capture(NULL), proc(allocProcessor(_method)) {}


Processor * BackgroundSubstraction::allocProcessor(const Method &_method)
{
    Processor * res(NULL);
    if( _method == id )
        res = new Processor();
    else if( _method == Basic_Method )
        res = new BasicMethod(true);
    else if( _method == Single_Gaussian_Distribution )
        res = new SingleGaussianDistribution(true);
    else if( _method == Mixture_Of_Gaussian )
        res = new MixtureOfGaussian();
    else if( _method == Lbp )
        res = new LBP(2.0);
    else if( _method == Optical_Flow )
        res = new OpticalFlow();

    return res;
}

void BackgroundSubstraction::setMethod(const Method &_method)
{
    method = _method;
}

Method BackgroundSubstraction::getMethod() const { return method; }

void BackgroundSubstraction::run()
{
    if( fileName == "CAM" )
        capture = cvCaptureFromCAM(0);
    else
        capture = cvCaptureFromFile(fileName.data());

    if(!capture)
        cout<<"pas de video en entree"<<endl;
    else
    {

    cvNamedWindow("Source", CV_WINDOW_AUTOSIZE);
    cvNamedWindow("Result", CV_WINDOW_AUTOSIZE);

    IplImage  * frame;
    int key;

    if(cvGrabFrame(capture))
    {
        frame = cvRetrieveFrame(capture);
        proc->init(frame);
        cvShowImage("Source",frame);
        cvShowImage("Result",proc->update(frame));
        key=cvWaitKey(0);
    }

    while(cvGrabFrame(capture))
    {
        frame = cvRetrieveFrame(capture);
        cvShowImage("Source",frame);
        cvShowImage("Result",proc->update(frame));
        key=cvWaitKey(20);
        if( key == 27 )
            break;
    }

    cvReleaseCapture(&capture);
    }

}


